import java.awt.Container;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
//import java.util.Calendar;
//import java.util.TimerTask;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class PlayVideoFrameTask implements Runnable {
	int img_width  = 320;
	int img_height = 240;
	int img_bpp    = 3;
	
	BufferedImage origImage;
	ByteBuffer buffer;
	FileInputStream fin;
	FileChannel fcin;
	JFrame frame;
	
	//static long last_time = 0;
	

	/*
	 * Class constructor - initializes video 
	 */
	PlayVideoFrameTask(String in_rgb_file, int vid_fps) throws IOException {
        origImage = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);

	    fin = new FileInputStream( in_rgb_file );
	    fcin = fin.getChannel();

	    buffer = ByteBuffer.allocateDirect( img_width * img_height * img_bpp );
	    
	    frame = new JFrame();
	    JLabel origImg = new JLabel(new ImageIcon(origImage));
	    Container contentPane = frame.getContentPane();
	    contentPane.add(origImg);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(img_width,img_height);
        frame.setVisible(true);
        
        //last_time = Calendar.getInstance().getTimeInMillis();
        
	}
	
	/* 
	 * Per-frame task, plays one video frame
	 * @see java.util.TimerTask#run()
	 */

	@Override
	public void run() {

        /*
         * Check for synch
         */
		long delta = Global.cur_vid_time - Global.cur_aud_time;
		//System.out.println("Time diff:" + (Global.cur_vid_time - Global.cur_aud_time));
		
		if(delta > Global.upper_threshold)
		{
			//Thread.yield();
			//return;
		}

		buffer.clear();
		
		//long now = Calendar.getInstance().getTimeInMillis();
		
		//System.out.println(now);
		
		//long delta = last_time - now;
		
        int res = 0;
		try {
			res = fcin.read( buffer );
		} catch (IOException e) {
			e.printStackTrace();
		}

        if (res==-1) {
            //this.cancel();
        }
        
        int ind = 0;
        
        //frame.setVisible(false);
        for(int y = 0; y < img_height; y++)
		{
			for(int x = 0; x < img_width; x++)
			{
				short r = (short) (buffer.get(ind) & 0xff);
				short g = (short) (buffer.get(ind+img_height*img_width) & 0xff);
				short b = (short) (buffer.get(ind+img_height*img_width*2) & 0xff);
				
				int pix = 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);

				// Setting RGB here
				origImage.setRGB(x,y,pix);

				ind++;
			}
		}
		frame.repaint();
		Global.cur_vid_time += 1000000/24;		
		
	}

}
